# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

# 国付通
APP_CONF = {
    '1306249881': {  # dwc 微信3.6%（100，200，300---1000），支付宝3.5%（10---3000）。d0结算
        'API_KEY': '9b08e138068e7fda69ed5d185019fe92df54fbbe',
        'gateway': 'http://www.go-pay.cn/Payment',
        'query_gateway': 'http://www.go-pay.cn/apiquery',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(d, key):
    s = 'version={}&mch_id={}&total_fee={}&out_trade_no={}&callback_url={}&jump_url={}&{}'.format(
        d['version'], d['mch_id'], d['total_fee'], d['out_trade_no'], d['callback_url'], d['jump_url'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_notify_sign(d, key):
    s = 'mch_id={}&status={}&sdpayno={}&out_trade_no={}&total_fee={}&service={}&{}'.format(
        d['mch_id'], d['status'], d['sdpayno'], d['out_trade_no'], d['total_fee'], d['service'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_query_sign(d, key):
    s = 'version={}&mch_id={}&out_trade_no={}&reqtime={}&{}'.format(
        d['version'], d['mch_id'], d['out_trade_no'], d['reqtime'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("gopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


# 微信扫码	weixin
# 微信公众号	gzhpay
# 微信wap	wxwap
# 支付宝扫码	alipay
# 支付宝wap	aliwap
# QQ扫码	qqrcode
# QQwap	qqwap
# 在线网银	bank
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'wxwap'
    elif service == 'alipay':
        payType = 'aliwap'
    elif service == 'qq':
        payType = 'qqwap'
    else:
        payType = 'bank'
    return payType


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    parameter_dict = OrderedDict((
        ('service', _get_pay_type(service)),
        ('version', '3.6'),
        ('mch_id', mch_id),
        ('out_trade_no', str(pay.id)),
        ('total_fee', '%.2f' % pay_amount),
        ('callback_url', '{}/pay/api/{}/gopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id)),
        ('jump_url', '{}/pay/api/{}/gopay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, mch_id)),
        ('body', 'charge'),
        ('attach', 'charge'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, key)
    _LOGGER.info("gopay create date: %s", parameter_dict)
    html_text = _build_form(parameter_dict, _get_gateway(mch_id))
    _LOGGER.info("gopay create html: %s", html_text)
    cache_id = redis_cache.save_html(pay.id, html_text)
    charge_resp = {
        'charge_info': settings.PAY_CACHE_URL + cache_id,
    }
    return charge_resp


# success
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("gopay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('gopay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = data['sdpayno']
    total_fee = float(data['total_fee'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 1:为成功，其他值为失败
    if trade_status == 1:
        _LOGGER.info('gopay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'version': '3.6',
        'mch_id': app_id,
        'out_trade_no': str(pay_id),
        'reqtime': local_now().strftime('%Y%m%d%H%M%S'),
        'get_code': 'json',
    }
    p_dict['sign'] = generate_query_sign(p_dict, key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=p_dict, headers=headers, timeout=10)
    _LOGGER.info(u'gopay query: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = int(data['status'])  # 0 订单未成功 1订单成功
        total_fee = float(data['total_fee'])
        trade_no = data['sdpayno']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 1:
            _LOGGER.info('gopay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('gopay data error, status_code: %s', response.status_code)
